package com.jy.oms.framework.asyn.task.checker;

import com.jy.oms.framework.asyn.task.checker.model.ExecutorCheckParam;
import com.jy.oms.framework.asyn.task.checker.model.ExecutorCheckResult;
import com.jy.oms.framework.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 判断任务是否能在指定时间规则下运行
 *
 * @author liuquan
 */
@Service
public class ExecuteTimeRulesChecker implements IExecutorChecker {
    private static Logger logger = LoggerFactory.getLogger(ExecuteTimeRulesChecker.class);

    @Autowired
    private ExecuteTimeRulesConfig executeTimeRulesConfig;

    @Override
    public int getExecutorCheckerOrder() {
        return IExecutorChecker.CHECKER_HIGHEST_ORDER + 20;
    }

    @Override
    public ExecutorCheckResult canExecute(ExecutorCheckParam executorCheckParam) {
        ExecuteTimeRulesConfig.ExecuteTimeRule taskExecuteTimeRule = executeTimeRulesConfig.getTaskExecuteTimeRule(executorCheckParam.getExecutorCode());
        if (taskExecuteTimeRule == null) {
            return ExecutorCheckResult.TRUE;
        }

        LocalTime current = LocalTime.now();
        if (taskExecuteTimeRule.getStartTime().isBefore(current)
                && taskExecuteTimeRule.getEndTime().isAfter(current)) {
            return ExecutorCheckResult.TRUE;
        }

        ExecutorCheckResult checkResult = new ExecutorCheckResult();
        checkResult.setResult(false);

        //任务最早时间需要重置为时间规则开始值
        if (taskExecuteTimeRule.getStartTime().isAfter(current)) {
            LocalDateTime earliest = LocalDateTime.of(LocalDate.now(), taskExecuteTimeRule.getStartTime());
            checkResult.setEarliestExecuteTime(DateUtils.localDate2Date(earliest));
        }

        //任务最早时间需要设置为第二天时间规则开始值
        if (taskExecuteTimeRule.getEndTime().isBefore(current)) {
            LocalDateTime earliest = LocalDateTime.of(LocalDate.now(), taskExecuteTimeRule.getStartTime());
            checkResult.setEarliestExecuteTime(DateUtils.localDate2Date(earliest.plusDays(1)));
        }

        return checkResult;
    }

}
